﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using MailSender.IndexMarkWcfServiceReference;
using System.Net;
using MailSender.Properties;

namespace MailSender
{
    class Program
    {
        private static IndexMarkServiceClient client = new IndexMarkServiceClient();
        private static System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ru-RU");

        static void Main(string[] args)
        {
            #if DEBUG
            DateTime Now = new DateTime(2010, 09, 17);
            #else
            DateTime Now = DateTime.Now;
            TimeSpan day = new TimeSpan(1, 0, 0, 0);
            Now = Now.Subtract(day);
            #endif

            AdmAnswerLog[] log = client.GetAnswerLog(Now, Now, null, true);
            SubscriberInfo[] subscribers = client.GetAllActivitySubscribers(Now, Now);

            string template = TemplateReader.GetContent("../../Templates/template.tpl");
            string templateTable = TemplateReader.GetContent("../../Templates/templateTable.tpl");

            foreach (SubscriberInfo subscriber in subscribers)
            {
                var logSubscriber = from l in log
                                    join r in subscriber.Respondents on l.Respondent.IDRespondent equals r.IDRespondent
                                    select l;

                if (logSubscriber.Count() == 0) continue;

                string mailText = string.Empty;

                foreach (AdmAnswerLog l in logSubscriber)
                {
                    mailText += TemplateProcessing.Replace(template,
                        new TplElement { keyWord = "Operation", value = TranslateOperation(l.Operation) },
                        new TplElement { keyWord = "Person", value= l.Respondent.Person.LastName },
                        new TplElement { keyWord = "DepartmentName", value= l.Respondent.Department.Abbriviation },
                        new TplElement { keyWord = "DateTime", value = string.Format(culture, "{0:dd.MM.yy, HH:ss}", l.CurrentTime) },
                        new TplElement { keyWord = "CharacteristicName", value = l.Characteristic.Name },
                        new TplElement { keyWord = "GradationsStr", value = string.Join("<br />", 
                            l.Gradations.Select(x => (x.Volume == null) ? x.GradationsStr : string.Format("{0} - {1}", x.GradationsStr, x.Volume))) },
                        new TplElement { keyWord = "Volume", value = Math.Round((double)(l.Volume ?? 0), Settings.Default.RoundPrecition) });
                }
                mailText = TemplateProcessing.Replace(templateTable,
                    new TplElement { keyWord = "Content", value = mailText });

                SendMail(string.Format("{0}", subscriber.Email), mailText);
            }

            #if DEBUG
            Console.WriteLine("Ok");
            Console.ReadKey();
            #endif
        }

        /// <summary>
        /// Отправка письма адресату
        /// </summary>
        /// <param name="to">Адресат</param>
        /// <param name="mailText">Текст письма в формате HTML</param>
        private static void SendMail(string to, string mailText)
        {
            SmtpClient s = new SmtpClient(Settings.Default.SMTPServerHost, Settings.Default.SMTPServerPort);
            s.UseDefaultCredentials = false;
            if (Settings.Default.Authentication == true)
            {
                s.Credentials = new NetworkCredential(Settings.Default.UserName, Settings.Default.Password);
            }
            s.DeliveryMethod = SmtpDeliveryMethod.Network;
            MailMessage m = new MailMessage(Settings.Default.MailSender, to, Settings.Default.MailSubject, mailText);
            m.IsBodyHtml = true;
            s.Send(m);
        }

        private static string TranslateOperation(AdmAnswerLogOperation operation)
        {
            switch(operation)
            {
                case AdmAnswerLogOperation.Deleted:
                    return "Удалено";
                case AdmAnswerLogOperation.Created:
                    return "Добавлено";
                case AdmAnswerLogOperation.Updated:
                    return "Отредактировано";
                default:
                    return string.Empty;
            }
        }
    }
}
